package com.iscas.lndicatormonitor.aop;

import com.iscas.lndicatormonitor.common.CustomResult;
import com.iscas.lndicatormonitor.domain.Audit;
import com.iscas.lndicatormonitor.dto.UsersDTO;
import com.iscas.lndicatormonitor.service.AuditService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class AuditLogAspect {
    @Autowired
    AuditService auditService;

    // 定义一个
    @Pointcut("within(@org.springframework.stereotype.Controller *) " +
            "|| within(@org.springframework.web.bind.annotation.RestController *)")
    public void controllerMethods() {
        // 方法体为空，作为切点的标识
    }

    // 在方法执行之前
    @Before("controllerMethods()")
    public void logBeforeControllerCall(JoinPoint joinPoint) {
        // 这里实现你的日志记录逻辑
    }

    // 在方法返回后执行
    @AfterReturning(pointcut = "controllerMethods()", returning = "result")
    public void logAfterControllerCall(JoinPoint joinPoint,Object result) {
        Audit audit = new Audit();
        CustomResult customResult = null;
        if (result instanceof CustomResult) {
             customResult = (CustomResult) result;
            // 现在你可以访问 CustomResult 类型的所有属性和方法
            // 例如
        }
        // 可以获取方法名、参数、返回值等信息，并记录到日志中
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = null;
        // 这里添加日志逻辑
        if (authentication != null && authentication.getPrincipal() instanceof UsersDTO && customResult != null) {
            UsersDTO userDetails = (UsersDTO) authentication.getPrincipal();
            audit.setOperateName(methodName);
            audit.setUserid(userDetails.getId());
            audit.setOperateTime(new Date());
            audit.setOperateResult(customResult.getStatus() == 40000 ? 2 : 1);
            // 这里你还可以获取 userDetails 的其他属性，如角色
            auditService.insert(audit);
        }
    }

}
